#!/bin/bash
PROG_NAME=$0
ACTION=$1
ACTIVE_PROFILE=$2
SERVICE_NAME=admin-service
JAR_NAME=${SERVICE_NAME}-0.0.1-SNAPSHOT.jar
usage() {
    echo "Usage: $PROG_NAME {[start|stop|restart] [setting_dev|setting_test|setting_prod]"
    exit 2
}
start_application() {
		echo "start ${SERVICE_NAME}..."
		procedure=`ps -ef | grep -w "${SERVICE_NAME}" |grep -w "java"| grep -v "grep" | awk '{print $2}'`
		if [[ "${procedure}" = "" ]];
		then
			if [[ "${ACTIVE_PROFILE}" = "" ]];
			then
				ACTIVE_PROFILE="setting_dev"
			fi
			echo "spring.profiles.active=${ACTIVE_PROFILE}"
			exec nohup java -jar -server -Xms1G -Xmx1G ${JAR_NAME} --spring.profiles.active=${ACTIVE_PROFILE} > log.log 0>&1 &
			echo "start ${SERVICE_NAME} success..."
		else
			echo "${SERVICE_NAME} is running..."
		fi
}
stop_application() {
		echo "stop ${SERVICE_NAME}..."
    procedure=`ps -ef | grep -w "${SERVICE_NAME}" |grep -w "java"| grep -v "grep" | awk '{print $2}'`
		if [[ "${procedure}" = "" ]];
		then
			echo "${SERVICE_NAME} is stopping..."
		else
			kill -9 ${procedure}
			sleep 1
			argProcedure=`ps -ef | grep -w "${SERVICE_NAME}" |grep -w "java"| grep -v "grep" | awk '{print $2}'`
			if [[ "${argProcedure}" = "" ]]; then
				echo "stop ${SERVICE_NAME} success..."
			else
				kill -9 ${argProcedure}
				echo "stop ${SERVICE_NAME} error"
			fi
		fi
}
start() {
    start_application
}
stop() {
    stop_application
}
case "$ACTION" in
    start)
        start
    ;;
    stop)
        stop
    ;;
    restart)
        stop
        start
    ;;
    *)
        usage
    ;;
esac